<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/11/13 14:47
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Api\V1\App\Customers;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Customers\CustomerRegisterRequest;
use App\Models\Customers\Customer;
use App\Models\Products\ProductDescription;
use App\Models\Setting;
use App\Services\Customers\Register\RegisterFactory;
use App\Services\EasySms\EasySmsService;
use App\Services\MobileApp\AppEnv;

class CustomerRegisterController extends ApiController
{
    /**
     * @param CustomerRegisterRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function register(CustomerRegisterRequest $request)
    {
        $telephone = $request->telephone;
        $dial_code = $request->dial_code ?: EasySmsService::COUNTRY_CODE_CN;

        $customer = new Customer;
        $customer->email = $request->email;
        $customer->password = $request->password;
        $customer->telephone = $telephone;
        $customer->dial_code = $dial_code;
        $customer->ip = $request->ip();
        $customer->verify_code = $request->verify_code;
        $customer->fullname = $request->fullname ?: $request->telephone ?: $request->email;

        // 检测手机号和国家区号是否唯一
        if ($telephone && $dial_code) {
            $this->checkUnless(
                (new Customer)->where('telephone', $telephone)->where('dial_code', $dial_code)->exists(),
                trans('customer.phone_exist')
            );
        }

        $service = RegisterFactory::create($request->type);

        $register = $service->register($customer);

        return $this->response(compact('register'));
    }

    /**
     *  app端 返回注册协议数据
     *
     * @return array|\Illuminate\Http\Response
     */
    public function show()
    {
        $language_id = AppEnv::languageId();

        $key = 'config_registration_agreement_'.$language_id.'_language';

        $register_agreement = Setting::getSettingSpecifyValue($key);

        // ENT_QUOTES 表示把 &#039; 转成 '
        $register_agreement = html_entity_decode($register_agreement, ENT_QUOTES, 'UTF-8');

        return $this->response(compact('register_agreement'));
    }

    /**
     * @deprecated (改用上面的方法了)
     *  app端 返回注册协议的blade模板
     *
     * @return array|\Illuminate\Http\Response
     */
    public function create()
    {
        $language_id = AppEnv::languageId();

        $key = 'config_registration_agreement_'.$language_id.'_language';

        $register_agreement = Setting::getSettingSpecifyValue($key);

        // ENT_QUOTES 表示把 &#039; 转成 '
        $register_agreement = html_entity_decode($register_agreement, ENT_QUOTES, 'UTF-8');

        return view('agreement.register', compact('register_agreement'));
    }
}